import router from "../router";
import {getToken} from "@/utils/auth";
import store from "@/store";
import {getObjArr, routerGo, saveObjArr} from "@/utils/role";
import Layout from "@/layout";


const whiteList = ['/login']
const role = store.state.setting.role

let getRouter

let toPath = {
    "router" : [
        {
            "path": "/",
            "component": "Layout",
            "redirect": "dashboard",
            "name": "dashboard",
            "meta": {
                "title": "首页",
                "icon": "el-icon-s-help"
            },
            "children": [
                {
                    "subId": "1486212318423212011",
                    "path": "dashboard",
                    "name": "Dashboard",
                    "component": "dashboard/index",
                    "meta": {
                        "title": "首页",
                        "icon": "el-icon-s-help"
                    }
                }
            ]
        },
    ]
}

router.beforeEach((to,form,next)=>{
    const hasToken =  getToken()
    if (hasToken){
        if (to.path === '/login') {
            next({path: '/'})
        }else {
            if (role){
                if (!getRouter) {
                    if (!getObjArr('router')) {
                        getRouter = toPath.router
                        saveObjArr('router', getRouter)
                        routerGo(to, next, getRouter)
                    } else {
                        getRouter = getObjArr('router')
                        routerGo(to, next, getRouter)
                    }
                } else {
                    next()
                }
            }else {
                next()
            }
        }
    }else {
        if (whiteList.indexOf(to.path) !== -1) {
            next()
        } else {
            next(`/login`)
        }
    }


})